using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using DualCameraApp.Models;
using Emgu.CV;
using System;
using System.Drawing;
using System.IO;
using System.Threading.Tasks;
using DualCameraApp.Services;
using SkiaSharp;

namespace DualCameraApp.ViewModels;

public partial class CameraViewModel : ObservableObject, IDisposable
{
    private CameraDevice _cameraDevice;
    private VideoRecorder _videoRecorder;
    private string _outputDirectory;

    [ObservableProperty] private int _cameraIndex;

    [ObservableProperty] private Avalonia.Media.Imaging.Bitmap? _currentFrame;

    [ObservableProperty] private bool _isRecording;

    [ObservableProperty] private bool _isCameraActive;

    [ObservableProperty] private bool _isChanging;

    [ObservableProperty] private string _statusMessage = "就绪";

    public CameraViewModel(int cameraIndex)
    {
        CameraIndex = cameraIndex;
        _outputDirectory = Path.Combine(Directory.GetCurrentDirectory(), "Captures");
        Directory.CreateDirectory(_outputDirectory);

        _cameraDevice = new CameraDevice(cameraIndex);
        _cameraDevice.FrameCaptured += OnFrameCaptured;
    }

    private void OnFrameCaptured(object sender, Mat frame)
    {
        // CurrentFrame = ImageConverterService.ConvertMatToAvaloniaBitmapByDraw(frame);
        CurrentFrame = ImageConverterService.ConvertMatToAvaloniaBitmapBySkia(frame);

        if (IsRecording)
        {
            _videoRecorder?.WriteFrame(frame);
        }
    }

    [RelayCommand]
    private void ToggleCamera()
    {
        if (IsCameraActive)
        {
            StopCamera();
        }
        else
        {
            StartCamera();
        }
    }

    public void StartCamera()
    {
        try
        {
            IsChanging = true;
            StatusMessage = "摄像头启动中";
            Task.Run(() =>
            {
                _cameraDevice.StartCapture();

                while (!_cameraDevice.IsRunning)
                    Task.Delay(100).Wait();

                IsCameraActive = true;
                StatusMessage = "摄像头运行中";
                IsChanging = false;
            });
        }
        catch (Exception ex)
        {
            StatusMessage = $"启动摄像头失败: {ex.Message}";
        }
    }

    public void StopCamera()
    {
        try
        {
            if (IsRecording)
            {
                StopRecording();
            }

            _cameraDevice.StopCapture();
            IsCameraActive = false;
            StatusMessage = "摄像头已停止";
        }
        catch (Exception ex)
        {
            StatusMessage = $"停止摄像头失败: {ex.Message}";
        }
    }

    [RelayCommand]
    public void CaptureImage()
    {
        if (!IsCameraActive)
        {
            StatusMessage = "请先启动摄像头";
            return;
        }

        try
        {
            string filename = $"Camera{CameraIndex}_Capture_{DateTime.Now:yyyyMMdd_HHmmss}.jpg";
            string fullPath = Path.Combine(_outputDirectory, filename);
            CaptureImageBySkia(fullPath);
            StatusMessage = $"已保存: {filename}";
        }
        catch (Exception ex)
        {
            Console.Write(ex);
            StatusMessage = $"拍照失败: {ex.Message}";
        }
    }

    private void CaptureImageByDraw(string fullPath)
    {
        var image = _cameraDevice.CaptureImageToBitmap();
        // string fullPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), filename);
        image.Save(fullPath);
    }

    private void CaptureImageBySkia(string fullPath)
    {
        var bitmap = _cameraDevice.CaptureImageToSKBitmap();
        using (var image = SKImage.FromBitmap(bitmap))
        using (var data = image.Encode(SKEncodedImageFormat.Png, 100))
        using (var stream = File.OpenWrite(fullPath))
        {
            data.SaveTo(stream);
        }
    }

    [RelayCommand]
    private void ToggleRecording()
    {
        if (IsRecording)
        {
            StopRecording();
        }
        else
        {
            StartRecording();
        }
    }

    public void StartRecording()
    {
        if (!IsCameraActive)
        {
            StatusMessage = "请先启动摄像头";
            return;
        }

        try
        {
            var frameSize = _cameraDevice.GetFrameSize();
            string filename = $"Camera{CameraIndex}_Recording_{DateTime.Now:yyyyMMdd_HHmmss}.mp4";
            string fullPath = Path.Combine(_outputDirectory, filename);

            _videoRecorder = new VideoRecorder(fullPath, frameSize.width, frameSize.height);
            _videoRecorder.StartRecording();
            IsRecording = true;
            StatusMessage = "录制中...";
        }
        catch (Exception ex)
        {
            Console.Write(ex);
            StatusMessage = $"开始录制失败: {ex.Message}";
        }
    }

    public void StopRecording()
    {
        try
        {
            _videoRecorder?.StopRecording();
            _videoRecorder?.Dispose();
            _videoRecorder = null;
            IsRecording = false;
            StatusMessage = "录制已停止";
        }
        catch (Exception ex)
        {
            StatusMessage = $"停止录制失败: {ex.Message}";
        }
    }

    public void Dispose()
    {
        StopRecording();
        StopCamera();
        _cameraDevice?.Dispose();
        GC.SuppressFinalize(this);
    }
}